import React from 'react';
import LazilyLoad, { importLazy } from 'components/lazilyLoad';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import css from './index.less';
import prepareModule from 'components/hoc/prepareModule';
import prepareThumbModule from 'components/hoc/prepareThumbModule';
import DIR from 'common/const/dir';

let modules = {};
/**
 * 页面内容渲染
 */
@observer
export default class PageContentRender extends React.Component {

  static propTypes = {
    mod: PropTypes.object.isRequired,
    isThumb: PropTypes.bool,
  };

  static defaultProps = {
    mod: { list: [] },
    isThumb: false, // 是否是右侧的缩略图
  };

  render() {
    const { mod: { list = [] }, isThumb } = this.props;
    // console.log(list);
    list.forEach((_mod) => {
      if (!modules[_mod.type]) {
        // console.log(_mod);
        const dir = DIR[_mod.type] || '';
        modules[_mod.type] = () => importLazy(import(`modules/${dir}${_mod.type}/render`));
      }
    });

    const props = {
      modules: {
        ...modules // 注意，这里必须要解构赋值
      },
    };

    return (
      <LazilyLoad {...props}>
        {
          ({...components}) => (
            <div className={css.pageContentRender}>
              {
                list.map((_mod, index) => {
                  const { type } = _mod;
                  if (components[type]) {
                    const C = isThumb ? prepareThumbModule(components[type], _mod) : prepareModule(components[type], _mod);
                    return <C key={index} mod={_mod} />;
                  }
                })
              }
            </div>
          )
        }
      </LazilyLoad>
    );
  }
}
